package com.leyou.controller;

import com.leyou.api.ActivityService;
import com.leyou.api.ReceiveService;
import com.leyou.constant.DefineException;
import com.leyou.constant.ResponseMessage;
import com.leyou.constant.Result;
import com.leyou.domain.db1entity.Couponactivity;
import com.leyou.domain.db1entity.Couponandactivity;
import com.leyou.domain.db3entity.LeyouCoupons;
import com.leyou.domain.db3entity.Prscard;
import com.leyou.domain.db3entity.Smssendcouponsinfo;
import com.leyou.domain.vo.CouponActivityInfoVO;
import com.leyou.domain.vo.ReceiveVO;
import com.leyou.utils.Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RequestMapping("home")
@RestController
public class ReceiveController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ActivityService activityService;


    @Autowired
    ReceiveService receiveService;


    @Autowired
    RabbitTemplate rabbitTemplate;


    @PostMapping("receive")
    ResponseMessage receive(@RequestBody ReceiveVO receiveVO) throws ParseException {

        if (!Utils.isNull(receiveVO.getActivitykey(), receiveVO.getPhone())) {

            //获取当前活动及优惠券列表
            CouponActivityInfoVO couponActivityInfoVO = receiveService.getCouponActivityInfo(receiveVO.getActivitykey());

            if (couponActivityInfoVO != null) {
                //存在当前活动
                //redis验证重复提交
                if (redisTemplate.hasKey(receiveVO.getActivitykey() + receiveVO.getPhone())) {
                    return Result.error(400006, "您提交的速度太快了，请休息一下");
                } else {
                    redisTemplate.opsForValue().set(receiveVO.getActivitykey() + receiveVO.getPhone(), "", 4, TimeUnit.SECONDS);
                    //验证活动期间
                    Date currentTime = new Date();
                    if (currentTime.compareTo(couponActivityInfoVO.getBegintime()) > 0) {
                        if (currentTime.compareTo(couponActivityInfoVO.getEndtime()) < 0) {
                            //活动优惠券有剩余
                            if (couponActivityInfoVO.getCount() > 0) {
                            } else {
                                return Result.error(400009, "当前活动优惠券已经被领完");
                            }
                        } else {
                            return Result.error(400008, "当前活动已结束");
                        }
                    } else {
                        return Result.error(400007, "当前活动还未开始");
                    }

                    //查询领取记录
                    if (activityService.checkReceive(receiveVO)) {
                        return Result.error(400010, "您已经参与过活动");
                    } else {

                        //验证是否注册
                        List<Prscard> prscardList = receiveService.getPrscardByPhone(receiveVO.getPhone());
                        //计算优惠券有效期
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date begintime = null;
                        Date endtime = null;
                        //计算优惠券有效期
                        if (couponActivityInfoVO.getDeadline() != null) {
                            //优惠券固定结束时间
                            begintime = sdf.parse(sdf.format(new Date()));
                            endtime = couponActivityInfoVO.getDeadline();
                        } else {
                            //优惠券固定持续时间
                            begintime = sdf.parse(sdf.format(new Date()));
                            endtime = Utils.getDateAfter(new Date(), couponActivityInfoVO.getDuration());
                        }

                        //发券
                        if (prscardList.size() > 1) {
                            //数据出现异常（不太可能出现的情况）
                            return Result.error(400011, "数据错误(会员表有多条记录与当前手机号对应)" + prscardList);
                        } else if (prscardList.size() < 1) {

                            //非注册会员
                            List<Smssendcouponsinfo> smssendcouponsinfoList = new ArrayList<>();
                            for (Couponandactivity couponandactivity : couponActivityInfoVO.getCouponandactivityList()) {
                                Smssendcouponsinfo smssendcouponsinfo = new Smssendcouponsinfo(2, 0, 0, Integer.valueOf(couponandactivity.getCouponkey()), couponandactivity.getAmount(), begintime, endtime, receiveVO.getPhone(), 623);
                                smssendcouponsinfoList.add(smssendcouponsinfo);
                            }
                            try {
                                receiveService.putSmsSendCoupons(smssendcouponsinfoList);
                            } catch (DefineException e) {
                                return Result.error(e.getErrorCode(), e.getMessage());
                            }
                            //产生发券消息
                            rabbitTemplate.convertAndSend("receiveQueue", receiveVO);
                            return Result.success(200004, "优惠券已冲入您的账户,请登录或注册账户使用");
                        } else {
                            //已注册会员
                            //拿到当前会员的idcard和userid
                            //向会员发券
                            List<LeyouCoupons> leyouCouponsList = new ArrayList<>();
                            for (Couponandactivity couponandactivity : couponActivityInfoVO.getCouponandactivityList()) {
                                LeyouCoupons leyouCoupons = new LeyouCoupons();
                                leyouCoupons.setStarttime(begintime);
                                leyouCoupons.setEndtime(endtime);
                                leyouCoupons.setValue(couponandactivity.getAmount());
                                leyouCoupons.setStatus("0");
                                leyouCoupons.setCardnum(prscardList.get(0).getCardnum());
                                leyouCoupons.setType(Integer.valueOf(couponandactivity.getCouponkey()));
                                leyouCoupons.setNumberCode(String.valueOf(System.currentTimeMillis()));
                                leyouCoupons.setUserId(prscardList.get(0).getBindUserid());
                                leyouCouponsList.add(leyouCoupons);
                            }
                            try {
                                receiveService.putLeyouCoupons(leyouCouponsList);
                            } catch (DefineException e) {
                                return Result.error(e.getErrorCode(), e.getMessage());
                            }

                            //发送生成记录的消息
                            rabbitTemplate.convertAndSend("receiveQueue", receiveVO);
                            return Result.success(200004, "恭喜你，领取成功！");
                        }
                    }
                }
            } else {
                return Result.error(400005, "数据错误当前活动不存在");
            }
        } else {
            return Result.error(400000, "参数为空");
        }
    }

    @PostMapping("getActivityById")
    public ResponseMessage getActivityById(@RequestBody Couponactivity couponactivity) {
        Couponactivity c = null;
        if (!StringUtils.isBlank(couponactivity.getActivitykey())) {

            try {
                c = activityService.getActivityById(couponactivity.getActivitykey());
            } catch (DefineException e) {
                return Result.success(e.getErrorCode(), e.getMessage());
            }
        }
        return Result.success(200000, "访问成功", c);
    }



}

